import type { UnpluginFactory } from 'unplugin'
import type { AutoRouterNode, AutoRouterOptions, PluginOptions } from '../types'
import { loadConfig } from 'unconfig'
import { createUnplugin } from 'unplugin'
import { CONFIG_FILE_SOURCE } from '../constants'
import { AutoRouter } from '../core'
import { injectName } from '../plugins/name'

export const unpluginFactory: UnpluginFactory<PluginOptions | undefined> = (options) => {
  const { config } = loadConfig.sync<AutoRouterOptions>({
    sources: {
      files: CONFIG_FILE_SOURCE,
    },
  })

  const autoRouter = new AutoRouter({ ...options, ...config })

  const autoRouterOptions = autoRouter.getOptions()

  return [
    {
      name: 'l-router',
      enforce: 'pre',
      vite: {
        apply: 'serve',
        async configureServer(server) {
          await autoRouter.generate()
          if (autoRouterOptions.watchFile) {
            autoRouter.watch()
          }
          autoRouter.setViteServer(server)
        },
      },
    },
    injectName(autoRouterOptions),
  ]
}

export const unplugin = /* #__PURE__ */ createUnplugin(unpluginFactory)

export default unplugin

export type { AutoRouterNode, AutoRouterOptions, PluginOptions }
